// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

// 记录用户逇浏览次数与（简单一点，每次增加次数就行）
const appealBrowseLog = async function (params) {
  const wxContext = cloud.getWXContext()

  // 需要用到事务，避免数据相互污染
  try {
    const result = await db.runTransaction(async transaction => {

      let appeal = await transaction.collection('appeal').doc(params.appealId).get()
      appeal = appeal.data


      if (appeal) {
        const updateAppeal = await transaction.collection('appeal').doc(params.appealId).update({
          data: {
            browseCount: appeal.browseCount+1
          }
        })

        // 会作为 runTransaction resolve 的结果返回
        return updateAppeal
        
      } else {
        // 会作为 runTransaction reject 的结果出去
        await transaction.rollback(false)
      }
    })

    return result
    
  } catch (e) {
    console.error(`transaction error`, e)

    return false
  }
}

module.exports = appealBrowseLog